package com.eduagent.xwqeduagent.api.GeneralImageEditing.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.model.CreateImageSynthesisTaskRequest;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.model.CreateImageSynthesisTaskResponse;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.model.GetImageSynthesisTaskResponse;
import com.eduagent.xwqeduagent.exception.BusinessException;
import com.eduagent.xwqeduagent.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class GeneralImageEditingApi {
    // 读取配置文件中的API Key
    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    // 创建任务地址
    public static final String CREATE_IMAGE_SYNTHESIS_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis";

    // 查询任务状态地址
    public static final String GET_IMAGE_SYNTHESIS_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 创建通用图像编辑任务
     * @param request 请求参数
     * @return 创建任务的响应
     */
    public CreateImageSynthesisTaskResponse createImageSynthesisTask(CreateImageSynthesisTaskRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }

        // 发送请求
        HttpRequest httpRequest = HttpRequest.post(CREATE_IMAGE_SYNTHESIS_TASK_URL)
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                // 必须开启异步处理，设置为enable
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(request));
        
        try (HttpResponse httpResponse = httpRequest.execute()) {
            if (!httpResponse.isOk()) {
                log.error("请求异常：{}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "通用图像编辑请求失败");
            }
            
            CreateImageSynthesisTaskResponse response = JSONUtil.toBean(httpResponse.body(), CreateImageSynthesisTaskResponse.class);
            String errorCode = response.getCode();
            if (StrUtil.isNotBlank(errorCode)) {
                String errorMessage = response.getMessage();
                log.error("通用图像编辑失败，errorCode:{}, errorMessage:{}", errorCode, errorMessage);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "通用图像编辑接口响应异常");
            }
            
            return response;
        }
    }

    /**
     * 查询通用图像编辑任务
     * @param taskId 任务ID
     * @return 任务查询结果
     */
    public GetImageSynthesisTaskResponse getImageSynthesisTask(String taskId) {
        if (StrUtil.isBlank(taskId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        }
        
        try (HttpResponse httpResponse = HttpRequest.get(String.format(GET_IMAGE_SYNTHESIS_TASK_URL, taskId))
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .execute()) {
            if (!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取任务失败");
            }
            
            return JSONUtil.toBean(httpResponse.body(), GetImageSynthesisTaskResponse.class);
        }
    }
} 